using System;
using System.Collections.ObjectModel;
using System.ServiceModel;
using System.ServiceModel.Channels;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;

using TrueCode.Core.Aspects;

namespace EMan.Server
{
  public class InstanceProviderBehavior : IServiceBehavior
  {
    private readonly Func< object > _factory;

    public InstanceProviderBehavior( [NotNull] Func< object > factory )
    {
      if( factory == null ) throw new ArgumentNullException( "factory" );
      _factory = factory;
    }

    #region IServiceBehavior Members
    public void Validate( ServiceDescription serviceDescription, ServiceHostBase serviceHostBase ){}

    public void AddBindingParameters( ServiceDescription serviceDescription, ServiceHostBase serviceHostBase,
                                      Collection< ServiceEndpoint > endpoints, BindingParameterCollection bindingParameters ){}

    public void ApplyDispatchBehavior( ServiceDescription serviceDescription, ServiceHostBase serviceHostBase )
    {
      foreach( var item in serviceHostBase.ChannelDispatchers )
      {
        var dispatcher = item as ChannelDispatcher;
        if( dispatcher != null )
          foreach( var endpoint in dispatcher.Endpoints )
            endpoint.DispatchRuntime.InstanceProvider = new EManServiceInstanceProvider( _factory );
      }
    }
    #endregion
  }
}